package com.guxingke.gblog.controller.front;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.guxingke.gblog.controller.BaseController;
import com.guxingke.gblog.dto.UserDto;
import com.guxingke.gblog.utilbean.MsgBean;

@Controller
@RequestMapping("/msg")
public class MsgController extends BaseController {

	@RequestMapping("/leaveMsg")
	public ModelAndView list() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("type", 1);
		mav.addObject("pid", 0);
		mav.addObject("replytype", 3);
		mav.addObject("msgs", msgService.getLeaveMsgs());
		mav.addObject("mainPage", "leavemsg/detail.jsp");
		mav.setViewName("home");
		return mav;
	}

	@RequestMapping("/save")
	public String save(
			@RequestParam(value = "articleId", required = false) Integer articleId,
			MsgBean msgBean, HttpSession session, HttpServletRequest request) {

		if ("".equals(msgBean.getUser().getNickname())
				|| "".equals(msgBean.getMsg().getContent())
				|| "".equals(msgBean.getUser().getEmail())) {
			request.setAttribute("error", "昵称、邮箱和内容不可为空");
			return "forward:/msg/leaveMsg.do";
		}

		UserDto currentUser = (UserDto) session.getAttribute("currentUser");
		if (currentUser != null) {
			int userId = currentUser.getId();
			msgBean.getMsg().setUserId(userId);
			msgService.saveMsg(msgBean.getMsg());
		} else {
			msgBean.getUser().setUsername(msgBean.getUser().getNickname());
			msgBean.getUser().setPassword(msgBean.getUser().getEmail());
			currentUser = userService.login(msgBean.getUser());
			if (currentUser == null) {
				msgBean.getUser().setImageName("default.jpg");
				userService.saveUser(msgBean.getUser());
				currentUser = userService.login(msgBean.getUser());
			}
			msgBean.getMsg().setUserId(currentUser.getId());
			msgBean.getMsg().setPubDate(new Date());

			System.out.println(msgBean);

			msgService.saveMsg(msgBean.getMsg());
		}
		if (msgBean.getMsg().getType() % 2 != 0) {
			return "redirect:/msg/leaveMsg.do";
		} else {
			return "redirect:/article/detail.do?articleId=" + articleId;
		}
	}
}
